<?php
/*
 module:		会员管理
 create_time:	2022-02-28 18:55:11
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\MoneyBalanceLog;
use app\api\model\Notice as NoticeModel;
use app\api\model\ZhAuthentication as ZhAuthenticationModel;
use app\api\model\ZhChat;
use app\api\model\ZhChatLog;
use app\api\model\ZhMatchmaker;
use app\api\model\ZhAuthParent;
use app\api\model\ZhCollection as ZhCollectionModel;
use app\api\model\ZhVipIntroduce;
use app\api\service\MemberService;
use app\api\model\Member as MemberModel;
use app\api\service\ZhMatchmakerService;
use app\backend\model\SysSite;
use app\backend\model\SysSite as SysSiteModel;
use EasyWeChat\Factory;
use app\api\model\ZhBalanceLog;
use app\api\service\MessageService;
use http\HttpExtend;

class Member extends Common
{


    function mockLogin() {
        $uid = $this->request->get('uid',386);
        $token = $this->setToken($uid);
        return $this->ajaxReturn($this->successCode, '返回成功', $token);
    }

    /**
     * @api             {get} /Member/view 01、查看详情
     * @apiGroup        Member
     * @apiVersion      1.0.0
     * @apiDescription  查看详情
     * @apiParam (输入参数：) {string}            uid 主键ID
     * @apiHeader {String} Authorization 用户授权token
     * @apiHeaderExample {json} Header-示例:
     * "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码 201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.data 返回数据详情
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":""}
     * @apiErrorExample {json} 02 失败示例
     * {"status":"201","msg":"没有数据"}
     */
    function view() {
        $data['uid'] = $this->request->uid;
        $field = '*';
        $res = checkData(MemberModel::field($field)->where($data)->find());
        $res['is_overdue'] = 0;
        if ($res['expires_time'] > time()) {
            $res['is_overdue'] = 1;
        }
        if ($res['expires_time']) {
            $res['expires_time'] = date('Y-m-d', $res['expires_time']);
        }

        if ($res['vip_id']) {
            $res['vip_name'] = \app\api\model\VipSys::where(['id' => $res['vip_id']])->value('vip_name');
        } else {
            $res['vip_name'] = '';
        }

        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }


    // 获取我的余额及我推广的会员
    function getMyData() {
        $wxapp_id = $this->request->get('wxapp_id');
        $uId = $this->request->uid;
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        $mapNum = [];
        $mapNum[1] = 0;
        $mapNum[2] = 0;
        $childUids = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id])->column('uid');
//        $resultM = ZhMatchmaker::whereIn('u_id', $childUids)->field('sex, COUNT(u_id) as num')->group('sex')->select();
//        foreach($resultM as $v){
//            $mapNum[$v['sex']] += $v['num'];
//        }
        if (!empty($childUids)) {
            $resultA = ZhAuthenticationModel::whereIn('u_id', $childUids)->field('gender, COUNT(authentication_id) as num') ->group('gender')->select();
            foreach ($resultA as $v) {
                $mapNum[$v['gender']] += $v['num'];
            }
        }


        /*
        $totalVipNum            = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id])//'is_vip' => 1
            ->count('uid');
        $nanVipNum              = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id,  'sex' => 1])//'is_vip' => 1,
            ->count('uid');
        $nvVipNum               = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id, 'sex' => 0])//'is_vip' => 1,
            ->count('uid');
        */
        $totalYuE = MoneyBalanceLog::where(['u_id' => $uId, 'wxapp_id' => $wxapp_id, 'type' => '收入', 'invalid' => 0])->sum('num');
        $totalVipNum =  MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id])->count();
        $user['total_vip_num'] = $totalVipNum;
        $user['nan_vip_num'] = $mapNum[1];
        $user['nv_vip_num'] = $mapNum[2];
        $authenticationNum = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id, 'is_authentication' => 1])->count();
        $parentsNum = MemberModel::where(['p_id' => $uId, 'wxapp_id' => $wxapp_id, 'is_parent' => 1])->count();
        $user['authentication_num'] = $authenticationNum; //佳人数量
        $user['parents_num'] = $parentsNum; //家长数量
        $user['total_yue'] = $totalYuE;
        $user['withdrawal_btn'] = $wxSetting['withdrawal_btn'];

        //我推荐的用户ID
        $userIds = MemberModel::where(['p_id' => $uId])->column('uid');
        if (!empty($userIds)) {
            $ZhMatchmakerNum = ZhMatchmaker::whereIn('u_id', $userIds)->count();
        }
        $user['matchmaker_num'] = $ZhMatchmakerNum ?? 0;

        return $this->ajaxReturn($this->successCode, '返回成功', $user);
    }


    /**
     * @api             {post} /Member/getOpenid 02、授权登录
     * @apiGroup        Member
     * @apiVersion      1.0.0
     * @apiDescription  创建数据
     * @apiParam (输入参数：) {string}
     * @apiParam (失败返回参数：) {object}        array 返回结果集
     * @apiParam (失败返回参数：) {string}        array.status 返回错误码  201
     * @apiParam (失败返回参数：) {string}        array.msg 返回错误消息
     * @apiParam (成功返回参数：) {string}        array 返回结果集
     * @apiParam (成功返回参数：) {string}        array.status 返回错误码 200
     * @apiParam (成功返回参数：) {string}        array.msg 返回成功消息
     * @apiSuccessExample {json} 01 成功示例
     * {"status":"200","data":"操作成功"}
     * @apiErrorExample {json} 02 失败示例
     * {"status":" 201","msg":"操作失败"}
     */
    function getOpenid() {
        $postField = 'code,wxapp_id,encryptedData,iv';
        $data = $this->request->only(explode(',', $postField), 'post', null);
        $site = SysSite::where(['wxapp_id' => $data['wxapp_id']])->find();

        $config = [
            'app_id' => $site['app_id'],
            'secret' => $site['app_secret'],
        ];

        try {
            $app = Factory::miniProgram($config);
            $res = $app->auth->session($data['code']);

            if (!isset($res['openid']) || !$res['openid']) {
                return $this->ajaxReturn($this->errorCode, '获取openid失败');
            }
            $res['expires_time'] = time() + $res['expires_in'];
            $user = MemberModel::where(['openid' => $res['openid'], 'wxapp_id' => $data['wxapp_id']])->find();

            if ($user) {
                $user['token'] = $this->setToken($user['uid']);
                return $this->ajaxReturn($this->successCode, '操作成功', $user);
            }
        } catch (\Exception $e) {

            return $this->ajaxReturn($this->errorCode, $e->getMessage());

        }

        return $this->ajaxReturn($this->successCode, '操作成功', $res);
    }

    /** h5 微信浏览器获取openid **/
    function getHOpenid() {
        $postField = 'code,wxapp_id';
        $data = $this->request->only(explode(',', $postField), 'post', null);
        $tJCode = $this->request->post('recommendUid', '', 'serach_in');

        $site = SysSite::where(['wxapp_id' => $data['wxapp_id']])->find();

        $config = [
            'app_id' => $site['official_account_appid'],
            'secret' => $site['official_account_appsecret'],
        ];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $config['app_id'] . '&secret=' . $config['secret'] . '&code=' . $data['code'] . '&grant_type=authorization_code';
        $result = json_decode(HttpExtend::get($url), true);

        if (isset($result['openid'])) {
            $url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $result['access_token'] . '&openid=' . $result['openid'] . '&lang=zh_CN';
            $result1 = json_decode(HttpExtend::get($url1), true);
            $memberData = MemberModel::where(['official_account_openid' => $result1['openid'], 'wxapp_id' => $data['wxapp_id']])->find();
            if (!$memberData) {
                $data = [
                    'wxapp_id' => $data['wxapp_id'],
                    'nickname' => $result1['nickname'],
                    'avatar' => $result1['headimgurl'],
                    'official_account_openid' => $result1['openid']
                ];
                if ($tJCode) {
                    $findMember = MemberModel::where(['wxapp_id' => $data['wxapp_id'], 'uid' => $tJCode, 'status' => 1])->find();
                    if ($findMember) {
                        $data['p_id'] = $tJCode;
                    }
                }
                $userID = MemberModel::insertGetId($data);
                if ($userID) {
                    $r = MemberModel::where(['wxapp_id' => $data['wxapp_id'], 'uid' => $userID])->find();
                    $r['token'] = $this->setToken($userID);
                    return $this->ajaxReturn($this->successCode, '登录成功', $r);
                }
            } else {
                $memberData['token'] = $this->setToken($memberData['uid']);
                return $this->ajaxReturn($this->successCode, '登录成功', $memberData);
            }
        } else {
            return $this->ajaxReturn($this->errorCode, '授权失败，请重试');
        }

    }

    /*start*/
    function login() {

        file_put_contents('login_data.txt', json_encode($this->_data));
        //is_authentication 1佳人 2佳人家长身份
        $postField = 'p_id,wxapp_id,nickname,avatar,encryptedData,iv,code,openid,session_key,is_matchmaker,is_authentication';
        $data = $this->request->only(explode(',', $postField), 'post', null);
        $pid = $this->request->post('p_id');
        $wxapp_id=$this->request->post('wxapp_id');
        $is_matchmaker=$this->request->post('is_matchmaker');
        $site = SysSite::where(['wxapp_id' => $data['wxapp_id']])->find();
        $avatar = $data['avatar'];
        $nickname = $data['nickname'];
        $config = [
            'app_id' => $site['app_id'],
            'secret' => $site['app_secret'],
        ];
        try {
            $app = Factory::miniProgram($config);
            $token = $app->access_token->getToken();
            $access_token = $token['access_token'];
            $code = $data['code'];

//            $code         = '8f08c96f52fa6d8418504d813a5df3a678d8ee05429b1aa05d910be12fd6dfd7';
            //test   temp

           $phoneDataRes = $app->access_token->request('https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $access_token, 'POST', [
                'json' => [
                    'code' => $code,
                ]
            ]);
            $phoneData = json_decode($phoneDataRes->getBody()->getContents(), true);
            $phoneData['access_token']=$access_token;
            if ($phoneData['errcode'] != 0) {
                return $this->ajaxReturn($this->errorCode,'获取手机号码失败', $phoneData);
            }
            $user = [
                'phoneNumber' => $phoneData['phone_info']['phoneNumber']
            ];

            if (!$data['openid']) {
                $res = $app->auth->session($data['code']);
                if (isset($res['openid'])) {
                    $data['openid'] = $res['openid'];
                }
            }
        } catch (\Exception $e) {
            return $this->ajaxReturn($this->errorCode, $e->getMessage());
        }
        $is_authentication = intval($data['is_authentication']);
        $member = MemberModel::where(['phone' => $user['phoneNumber'], 'wxapp_id' => $data['wxapp_id']])->find();
        $uid = $member['uid'];
        $user_data = [
            'phone' => $user['phoneNumber'],
            'wxapp_id' => $data['wxapp_id'],
            'is_matchmaker' => $data['is_matchmaker'],
        ];
        //佳人身份
        if($is_authentication == 1){
            $user_data['is_authentication'] = 1;
        //家长身份
        }elseif($is_authentication == 2){
            $user_data['is_parent'] = 1;
        }
        if ($data['openid']) {
            $user_data['openid'] = $data['openid'];
        }

        if ($member) {
            MemberModel::where(['uid' => $uid])->update($user_data);
        } else {
            //邀请我的人的uid
            if ($pid) {
                $user_data['p_id'] = $pid;
            }
            //注册用户添加积分
            $currency = \app\backend\model\ZhCurrencySet::where(['wxapp_id' => $wxapp_id])->find();
            if ($currency) {
                $user_data['virtual_currency_balance'] = $currency["register_num"];
            }
            $user_data['create_time'] = time();
            $uid = MemberModel::insertGetId($user_data);
            //添加notice
            $notice_data=[
                'wxapp_id' => $wxapp_id,
                'createtime'=>time(),
                'u_id'=>$uid,
                'type'=>4,//1红娘 2佳人 3家长 4用户
                'status'=>'0',//0未读 1已读
                'content'=>'您有一条待审核的"用户"申请，点击待审核的通知后，提醒数量减少'

            ];
            $notice_id=NoticeModel::insertGetId($notice_data);
            //邀请成功，给邀请人发一条通知
            if(intval($pid)>0){
                $type_name="佳人";
                //发起通知
                if($is_authentication == 1){
                    $type_name= "佳人";
                    //家长身份
                }elseif($is_authentication == 2){
                    $type_name= "家长";
                }
                if(intval($is_matchmaker)>0){
                    $type_name= "红娘";
                }
                $notice["wxapp_id"]=$wxapp_id;
                $notice["u_id"]=0;//发送人id
                $notice['s_id'] =$pid;//接收人
                $notice['create_time'] =date("Y-m-d H:i:s");
                $notice['status'] =1;
                $c_id = ZhChat::insertGetId($notice);
                if($c_id){
                    $content="恭喜！您已成功邀请{$user['phoneNumber']}注册为{$type_name}。".date("Y-m-d H:i:s");
                    $log["wxapp_id"]=$wxapp_id;
                    $log["chat_id"]=$c_id;
                    $log["type"]="text";
                    $log["content"]=$content;
                    $log["add_time"]=date("Y-m-d H:i:s");
                    $log["u_id"]=$pid;
                    $log["is_read"]=0;
                    $log["record_time"]=date("H:i",time());
                    $c_log_id=ZhChatLog::insertGetId($log);
                }
            }

        }
        //添加红娘 佳人数据
        $is_matchmaker = intval($data['is_matchmaker']);
        if ($is_matchmaker == 1) {
            $matchmaker = \app\api\model\ZhMatchmaker::where(["u_id" => $uid])->find();
            if (!$matchmaker) {
                $z_data['u_id'] = $uid;
                $z_data['wxapp_id'] = $data['wxapp_id'];
                $z_data['level_id'] = 26;//默认普通红娘
                //test   temp
                $z_data['phone'] = $phoneData['phone_info']['phoneNumber'];
                //  $z_data['phone'] ='17762280847';
                $z_data['head_portrait'] = $avatar;
                //上级推荐人处理
                $z_data['top_matchmaker_id'] = 0;
                if ($data['p_id'] > 0) {
                    $tmpMaker = \app\api\model\ZhMatchmaker::where(["u_id" => $data['p_id']])->find();
                    if($tmpMaker){
                        $z_data['top_matchmaker_id'] = $tmpMaker['matchmaker_id'];
                    }

                }

                $res = ZhMatchmakerService::add($z_data);
                //添加notice
                $notice_data=[
                    'wxapp_id' => $data['wxapp_id'],
                    'createtime'=>time(),
                    'u_id'=>$uid,
                    'type'=>1,//1红娘 2佳人 3家长 4用户
                    'status'=>'0',//0未读 1已读
                    'content'=>'您有一条待审核的"红娘"申请，点击待审核的通知后，提醒数量减少'

                ];
                $notice_id=NoticeModel::insertGetId($notice_data);
            }
        }
        //佳人身份，添加佳人数据
        if ($is_authentication == 1) {
            $authentication = \app\api\model\ZhAuthentication::where(["u_id" => $uid])->find();
            if (!$authentication) {
                $a_data['u_id'] = $uid;
                $a_data['createtime'] = time();
                $a_data['wxapp_id'] = $data['wxapp_id'];
                $a_data['contacts'] = $phoneData['phone_info']['phoneNumber'];
                $a_data['head_portrait'] = $avatar;
                if ($data['p_id'] > 0) {
                    $tmpMaker = \app\api\model\ZhMatchmaker::where(["u_id" => $data['p_id']])->find();
                    $a_data['matchmaker_id'] = $tmpMaker['matchmaker_id'];
                }
                $authentication_id = ZhAuthenticationModel::create($a_data);
                //添加notice
                $notice_data=[
                    'wxapp_id' => $data['wxapp_id'],
                    'createtime'=>time(),
                    'u_id'=>$uid,
                    'type'=>2,//1红娘 2佳人 3家长 4用户
                    'status'=>'0',//0未读 1已读
                    'content'=>'您有一条待审核的"佳人"申请，点击待审核的通知后，提醒数量减少'

                ];
                $notice_id=NoticeModel::insertGetId($notice_data);
            }
         //佳人家长身份，添加家长数据
        } elseif ($is_authentication == 2) {
            $auth_parent = ZhAuthParent::where(["u_id" => $uid])->find();
            if (!$auth_parent) {
                $p_data['u_id'] = $uid;
                $p_data['createtime'] = time();
                $p_data['wxapp_id'] = $data['wxapp_id'];
                $p_data['gender'] = 0;
                $p_data['contacts'] = $phoneData['phone_info']['phoneNumber'];
                $p_data['head_portrait'] =$avatar;
                $parentid_id = ZhAuthParent::create($p_data);
            }
        }
        $user = MemberModel::find($uid);
        $authentication = ZhAuthenticationModel::field("authentication_id")->where(["u_id" => $uid])->find();
        if ($authentication) {
            $user["authentication_id"] = $authentication["authentication_id"];
        } else {
            $user["authentication_id"] = 0;
        }
        $auth_parent = ZhAuthParent::field("id")->where(["u_id" => $uid])->find();
        if ($auth_parent) {
            $user["auth_parent_id"] = $auth_parent["id"];
        } else {
            $user["auth_parent_id"] = 0;
        }
        //如果是红娘，关联上红娘记录
        $matchmaker = \app\api\model\ZhMatchmaker::field("matchmaker_id")->where(["u_id" => $uid])->find();
        if ($matchmaker) {
            $user["matchmaker_id"] = $matchmaker["matchmaker_id"];
        } else {
            $user["matchmaker_id"] = 0;
        }
        $user['token'] = $this->setToken($uid);
        $user['is_authentication'] = $data['is_authentication'];//识别登陆佳人还是家长
        return $this->ajaxReturn($this->successCode, '登录成功', $user);
    }

    //授权获取头像的时候调用
    public function editInfo() {
        $postField = 'wxapp_id,nickName,avatarUrl,openid';
        $params = $this->request->only(explode(',', $postField), 'post', null);

        $uid = $this->request->uid;
        $user = MemberModel::find($uid);
        $data = [];
        $data['nickname'] = $params['nickName'];
        $data['avatar'] = $params['avatarUrl'];
        //完善资料添加积分
        $currency = \app\backend\model\ZhCurrencySet::where([
                                                                'wxapp_id' => $params['wxapp_id']
                                                            ])->find();
        if ($currency) {
            $data['virtual_currency_balance'] = $currency["register_num"] + $user["virtual_currency_balance"];
        }
        MemberModel::where(['uid' => $uid])->update($data);

        //同步到佳人和红娘的表
        ZhAuthenticationModel::where('u_id', $uid)->update(['head_portrait' => $params['avatarUrl']]);
        ZhMatchmaker::where('u_id', $uid)->update(['head_portrait' => $params['avatarUrl']]);
        $user = MemberModel::find($uid);
        return $this->ajaxReturn($this->successCode, '成功', $user);
    }
    /*end*/

    //单纯编辑头像
    public function editAvatar() {
        $uid = $this->request->uid;
        $postField = 'user_type, avatar';
        $params = $this->request->only(explode(',', $postField), 'post', null);
        if (empty($params['avatar'])) {
            return $this->ajaxReturn($this->errorCode, '头像不能为空');
        }
        //同步到佳人和红娘的表
        if ($params['user_type'] == 1) {
            ZhAuthenticationModel::where('u_id', $uid)->update(['head_portrait' => $params['avatar']]);
        }
        if ($params['user_type'] == 2) {
            ZhMatchmaker::where('u_id', $uid)->update(['head_portrait' => $params['avatar']]);
        }
        return $this->ajaxReturn($this->successCode, '成功');
    }


    /**APP注册**/
    public function register() {
        $wxapp_id = $this->request->post('wxapp_id');
        $phone = $this->request->post('phone', '', 'serach_in');
        $code = $this->request->post('code', '', 'serach_in');
        $pwd = $this->request->post('password', '', 'serach_in');
        $tJCode = $this->request->post('recommendCode', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if (!$phone) {
            return $this->ajaxReturn($this->errorCode, '缺少电话');
        }
        $mData = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->find();
        if ($mData) {
            return $this->ajaxReturn($this->errorCode, '该手机号已被注册');
        }
        if (!$code) {
            return $this->ajaxReturn($this->errorCode, '缺少验证码');
        }
        $MessageService = new MessageService($wxapp_id);
        $res = $MessageService->checkVerifyCode($code, $phone);
        if (!$res) {
            return $this->ajaxReturn($this->errorCode, '验证码错误');
        }

        if (!$pwd) {
            return $this->ajaxReturn($this->errorCode, '缺少密码');
        }
        if ($tJCode) {
            $findMember = MemberModel::where(['wxapp_id' => $wxapp_id, 'uid' => $tJCode, 'status' => 1])->find();
            if ($findMember) {
                $res = MemberModel::insert(['wxapp_id' => $wxapp_id, 'pwd' => md5($pwd), 'phone' => $phone, 'p_id' => $tJCode]);
                if ($res) {
                    return $this->ajaxReturn($this->successCode, '注册成功');
                }
            }
        }
        $res = MemberModel::insert(['wxapp_id' => $wxapp_id, 'pwd' => md5($pwd), 'phone' => $phone]);
        if ($res) {
            return $this->ajaxReturn($this->successCode, '注册成功');
        }
    }


    /**APP登录**/
    public function appLogin() {
        //        var_dump(123);
        file_put_contents('login_data.txt', json_encode($this->_data),FILE_APPEND);
        $wxapp_id = $this->request->post('wxapp_id');
        $phone = $this->request->post('phone', '', 'serach_in');
        $code = $this->request->post('code', '', 'serach_in');
        $pwd = $this->request->post('password', '', 'serach_in');
        $post_param=$this->request->post();
        //默认账号密码登陆
        $type = $this->request->post('type', '1000', 'serach_in');
        $oOpenid = $this->request->post('official_account_openid', '', 'serach_in');
        if (!$wxapp_id) {
            file_put_contents('login_data.txt'," 缺少平台参数： ". json_encode($this->_data),FILE_APPEND);
            return $this->ajaxReturn($this->errorCode, '缺少平台参数',$post_param);
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {

            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if (!$phone) {
            return $this->ajaxReturn($this->errorCode, '缺少电话');
        }
        $mData = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->find();
        if (!$mData) {
            return $this->ajaxReturn($this->errorCode, '手机号未注册，请先注册');
        }

        if (!$pwd && $type == '1000') {
            return $this->ajaxReturn($this->errorCode, '缺少密码');
        }
        /**
         * h5在微信浏览器登录并获取openid--start
         **/
        if ($oOpenid) {
            MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->update(['official_account_openid' => $oOpenid]);
        }
        /**
         * h5在微信浏览器登录并获取openid--end
         **/
        if ($type == '1000') {
            $res = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone, 'pwd' => md5($pwd)])->find();
        } elseif ($type == '2000') {
            $MessageService = new MessageService($wxapp_id);

            $re = $MessageService->checkVerifyCode($code, $phone);

            if (!$re) {
                return $this->ajaxReturn($this->errorCode, '验证码错误');
            } else {
                $res = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->find();
            }
        }
        if ($res) {
            $res['token'] = $this->setToken($res['uid']);
            return $this->ajaxReturn($this->successCode, '登录成功', $res);
        } else {
            return $this->ajaxReturn($this->errorCode, '账号或密码错误');
        }
    }


    /**发送短信**/
    public function SendSMS() {
        $wxapp_id = $this->request->post('wxapp_id');
        $phone = $this->request->post('phone', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if (!$phone) {
            return $this->ajaxReturn($this->errorCode, '缺少电话');
        }
        $MessageService = new MessageService($wxapp_id);

        $res = $MessageService->sendVerifyCode($phone);
        return $this->ajaxReturn($this->successCode, '发送成功', $res);
    }

    /**APP修改密码**/
    public function editPwd() {
        $wxapp_id = $this->request->post('wxapp_id');
        $phone = $this->request->post('phone', '', 'serach_in');
        $code = $this->request->post('code', '', 'serach_in');
        $pwd = $this->request->post('password', '', 'serach_in');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if (!$phone) {
            return $this->ajaxReturn($this->errorCode, '缺少电话');
        }
        $mData = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->find();
        if (!$mData) {
            return $this->ajaxReturn($this->errorCode, '手机号错误，请重新输入');
        }
        if (!$code) {
            return $this->ajaxReturn($this->errorCode, '缺少验证码');
        }
        $MessageService = new MessageService($wxapp_id);

        $codeRes = $MessageService->checkVerifyCode($code, $phone);
        if (!$codeRes) {
            return $this->ajaxReturn($this->errorCode, '验证码错误');
        }
        if (!$pwd) {
            return $this->ajaxReturn($this->errorCode, '缺少密码');
        }
        $res = MemberModel::where(['wxapp_id' => $wxapp_id, 'phone' => $phone])->update(['pwd' => md5($pwd)]);
        if ($res) {
            return $this->ajaxReturn($this->successCode, '修改成功');
        } else {
            return $this->ajaxReturn($this->errorCode, '修改失败');
        }

    }


    function index() {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        // 获取用户id 用以判断用户是否登录
        $token = $this->request->header('Authorization');
        //print_r($token);exit;
        //$token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbGllbnQueGhhZG1pbiIsImF1ZCI6InNlcnZlci54aGFkbWluIiwiaWF0IjoxNzE3OTc5ODQxLCJleHAiOjE3MTgwNjYyNDEsInVpZCI6NTI3fQ.rrdUJbRHonynnz3D67mbYwBM79sorAGryOsS39N_2e4';
        $uid = 0;
        if ($token) {
            $jwt = Jwt::getInstance();
            $jwt->setIss(config('my.jwt_iss'))->setAud(config('my.jwt_aud'))
                ->setSecrect(config('my.jwt_secrect'))
                ->setToken($token);
            $uid = $jwt->decode()->getClaim('uid');
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '未知用户');
            }
        }

        $limit = $this->request->get('limit', 4, 'intval');
        $page = $this->request->get('page', 1, 'intval');
        $show_home = $this->request->get('show_home', 0, 'intval');

        $where = [];
        $where['wxapp_id'] = $wxapp_id;
        $where['auth_status'] = 2;

        $model = MemberModel::where($where);
        if ($show_home) {
            $model->where('top_card_expiry', '>=', time());
        }
        $field = 'uid,avatar,s_desc,top_card_expiry,nickname,phone,openid,real_name,tags,pictures,height,age';
        $res = $model->field($field)->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        $data = $res['data'];
        foreach ($data as &$datum) {
            $datum['tags'] = empty($datum['tags']) ? [] : explode(',', $datum['tags']);
            $datum['pictures'] = empty($datum['pictures']) ? [] : json_decode(htmlspecialchars_decode($datum['pictures']), true);

            if (!empty($uid)) {
                $ZhCollectionData = ZhCollectionModel::where(['u_id' => $uid, 'wxapp_id' => $wxapp_id, 'release_id' => $datum['uid']])->find();
                if ($ZhCollectionData) {
                    $datum['is_collection'] = $ZhCollectionData['status'];
                } else {
                    $datum['is_collection'] = 0;
                }
            } else {
                $datum['is_collection'] = 0;
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功', ['list' => $data, 'count' => $res['total']]);
    }


    /**
     * 会员介绍
     */
    public function introduce() {
        $wxapp_id = $this->request->get('wxapp_id');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

        $intru=ZhVipIntroduce::select();
        foreach ($intru as &$i){
            $i['videos'] = json_decode(htmlspecialchars_decode( $i['videos']),  true);
        }
        return $this->ajaxReturn($this->successCode, '返回成功',
             $intru);
    }


    public function getOpenIdNew() {
        $postField = 'code,wxapp_id';
        $data = $this->request->only(explode(',', $postField), 'post', null);
        $site = SysSite::where(['wxapp_id' => $data['wxapp_id']])->find();

        $config = [
            'app_id' => $site['app_id'],
            'secret' => $site['app_secret'],
        ];

        try {
            $app = Factory::miniProgram($config);
            $res = $app->auth->session($data['code']);

            if (!isset($res['openid']) || !$res['openid']) {
                return $this->ajaxReturn($this->errorCode, '获取openid失败');
            }

        } catch (\Exception $e) {

            return $this->ajaxReturn($this->errorCode, $e->getMessage());
        }

        return $this->ajaxReturn($this->successCode, '操作成功', $res['openid']);
    }

    /**
     * 红娘邀请明细
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getMatchmakerData() {
        $op= $this->request->get('op');
        $wxapp_id = $this->request->get('wxapp_id');
//        $uId      = $this->request->uid;
        $uId = $this->getUid();
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSite::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }
        if($op=="test"){
            $uId=520;
            $user = MemberModel::where(['uid' => 520, 'wxapp_id' => $wxapp_id])->find();
        }else{
            $user = MemberModel::where(['uid' => $uId, 'wxapp_id' => $wxapp_id])->find();
        }

        if (!$user) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }
        $matchMaker_info = ZhMatchmaker::where(['u_id' => $uId])->find();
        //初始化返回数据
        $result = [
            'effect_num' => 0,
            'no_effect_num' => 0,
            'effect_list' => [],
            'no_effect_list' => []
        ];

        $effectList = [];  //已生效，有效资料数，已经审核的达到10份，这个时候flag=1
        $noEffectList = []; //未生效
        if ($matchMaker_info) {
            $userIds = MemberModel::where('p_id', $uId)->column('uid');

            if ($userIds) {
                $list = ZhMatchmaker::alias('a')->whereIn('u_id', $userIds)
                   ->leftJoin('member m ', 'm.uid = a.u_id')
                    ->field('a.flag,a. matchmaker_id,  a.phone, a.createtime,m.nickname')
                    ->select()->toArray();
                foreach ($list as $value) {
                    $value['createtime'] = date('Y-m-d H:i:s', $value['createtime']);
                    if ($value['flag'] == 1) {
                        $effectList[] = $value;
                    } else {
                        $noEffectList[] = $value;
                    }
                }
            }

            $result = [
                'effect_num' => count($effectList),//已生效数量
                'no_effect_num' => count($noEffectList),//未生效数量
                'effect_list' => $effectList,//已生效列表
                'no_effect_list' => $noEffectList//未生效列表
            ];
        }

        return $this->ajaxReturn($this->successCode, '返回成功', $result);
    }


    //家长列表
    function parents()
    {
        $uid = $this->request->uid;
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $res = \app\api\model\Member::where('p_id', $uid)->where('is_parent', 1)->field('nickname,phone,create_time')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        foreach ($res['data'] as &$v) {
            $v['create_time'] = date('Y-m-d', $v['create_time']);
        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }

    //佳人列表
    function authentication(){
        $uid = $this->request->uid;
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $res = \app\api\model\Member::where('p_id', $uid)->where('is_authentication', 1)->field('nickname,phone,create_time')->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        foreach ($res['data'] as &$v) {
            $v['create_time'] = date('Y-m-d', $v['create_time']);
        }
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }


}

